package com.example.schoolexam2.controller;

import com.example.schoolexam2.entity.PageVO;
import com.example.schoolexam2.service.PageService;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/page")
public class PageController {
    @Autowired
    PageService pageService;

    @RequestMapping("/getPages")
    Map<String,Object> getPages(@RequestBody String obj){
        PageVO page = formatPageVo(obj);
        Map<String,Object> map = new HashMap<>();
        map.put("datas",pageService.selectPages(page.getPname()));
        map.put("total",pageService.getPageCount(page.getPname()));
        return map;
    }

    @RequestMapping("/addPages")
    Map<String,Object> addPages(@RequestBody String obj){
        PageVO page = formatPageVo(obj);
        Map<String,Object> map = new HashMap<>();
        map.put("msg",pageService.addPage(page));
        return map;
    }

    @RequestMapping("/updatePages")
    Map<String,Object> updatePages(@RequestBody String obj){
        PageVO page = formatPageVo(obj);
        Map<String,Object> map = new HashMap<>();
        map.put("msg",pageService.updatePage(page));
        return map;
    }

    @RequestMapping("/deletePages")
    Map<String,Object> deletePages(@RequestBody String obj){
        Gson gson = new Gson();
        List<PageVO> list = gson.fromJson(String.valueOf(obj), new TypeToken<List<PageVO>>() {}.getType());
        Map<String,Object> map = new HashMap<>();
        int result = 0;
        for(int i=0;i<list.size();i++){
            if(pageService.deletePage(list.get(i))>0){
                result++;
            }
        }
        map.put("msg","成功删除了"+result+"条数据");
        return map;
    }

    private PageVO formatPageVo(String obj){
        Gson gson = new Gson();
        PageVO page = new PageVO();
        return page = gson.fromJson(obj,PageVO.class);
    }

}
